package com.company.ddd.infrastructure.persistence.hibernate;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

/**
 * Functionality common to all Hibernate repositories.
 */
public abstract class HibernateRepository {

    protected Logger log = LoggerFactory.getLogger(getClass());


    @Autowired
    public SessionFactory sessionFactory;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * 子类通过此方法获取Criteria,设置查询条件后把Criteria当作参数调用
     *
     * @param clazz
     * @return
     */
    public Criteria getCriteria(Class clazz) {
        return getSession().createCriteria(clazz);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     */

    public void delete(Object entity) {
        getSession().delete(entity);
        log.info("数据库删除记录");
    }

    /**
     * 保存对象
     *
     * @param entity 实体对象
     * @return 主键
     */

    public Serializable save(Object entity) {
        Serializable tkey = getSession().save(entity);
        log.info("数据库新增记录");
        return tkey;
    }

    /**
     * 更新对象
     *
     * @param entity 实体对象
     */
    public void update(Object entity) {
        getSession().update(entity);
        log.info("数据库修改记录");
    }


}
